# -*- coding: UTF-8 -*-
# cython: language_level=3
import socket
import struct

from tqdm import tqdm

from utils.ip.xdbSearcher import XdbSearcher

ip_db = None


def ip_str2int(ip):
    int_ip = struct.unpack('!I', socket.inet_aton(ip))[0]
    print(ip, '->', int_ip)
    return int_ip


def ip_int2str(int_ip):
    str_ip = socket.inet_ntoa(struct.pack('!I', int_ip))
    return str_ip


def fix_cz88(file_path):
    with open(file_path) as f:
        lines = f.readlines()
    r = []
    for line in tqdm(lines, desc='Reading cz88...'):
        # 223.255.253.0   223.255.253.255 中国–贵州–贵阳 贵安新区电信天翼云计算数据中心
        # 222.88.188.233  222.88.188.233  中国–四川–自贡–贡井区–成佳镇 电信/联众网吧网吧(成佳镇大同街29号)
        if 'CloudFlare' in line or 'IANA' in line or 'DNS' in line:
            continue
        ip_start = line[:15].rstrip()
        ip_end = line[16:31].rstrip()

        address = line[32:].replace('CZ88.NET', '').strip()
        address, _, isp = address.partition(' ')
        _address = ['0', '0', '0', '0']
        for i, d in enumerate(address.split('–')):
            if i < 4:
                _address[i] = d
            else:
                _address[3] += d

        country, province, city, area = _address
        isp = isp or '0'
        # 国家|区域|省份|城市|ISP
        r.append('|'.join([ip_start, ip_end, country, '0', province, city, isp]) + '\n')

    with open(file_path + '.fix', 'w', encoding='utf-8') as f:
        f.writelines(r)


def find_ip(ip):
    global ip_db
    if ip_db is None:
        try:
            ip_db = XdbSearcher(contentBuff=XdbSearcher.loadContentFromFile(dbfile=r'utils/ip/ip_2407.xdb'))
        except:
            raise Exception('ip_db not found')
        else:
            print('ip_db load ok')

    region_str = ip_db.searchByIPStr(ip)
    # print(region_str)
    country, _, province, city, isp = region_str.split('|')
    province = '' if province == '0' else province
    city = '' if city == '0' else city
    country = '' if country == '0' else country
    isp = '' if isp == '0' else isp

    return country, province, city, isp


# 解析域名，获取IP地址
def get_ip_address(domain_name):
    return socket.gethostbyname(domain_name)


if __name__ == '__main__':
    # print(ip_str2int('221.192.178.69'))

    # fix_cz88(r"C:\Users\Administrator\Desktop\1.txt")

    # result = find_ip('8.8.8.8')
    # print(result)

    # import requests
    # rsp = requests.get("http://www.baidu.com", stream=True)
    # print(rsp.raw._connection.sock.getpeername()[0])
    # print(rsp.text)

    print(get_ip_address('www.baisdu.com'))
